var app = sm("do_App");
var page = sm("do_Page");
var hashdata = mm("do_HashData");
var open = require("helper/open");
var httpSilence = require("helper/httpSilence");
var circleUrl = require("url/circle");
var imHelper = require("helper/im");
var circleHelper = require("helper/circle");

page.on("back", function(data) {
	app.fire("closeChatPage", {chat_close:true,chat_to:chatTo});
	app.closePage({chat_back:true,chat_type:chatType,chat_to:chatTo});
})

page.on("loaded",function(){
})

//点击头部-隐藏键盘
ui("$").on("touch", function(data, e) {
	page.hideKeyboard();
})

ui("headerLeft").on("touch", function() {
	app.fire("closeChatPage", {chat_close:true,chat_to:chatTo});
	app.closePage({chat_back:true,chat_type:chatType,chat_to:chatTo});
});

var chatType = null;//对话类型(Chat/GroupChat)
var chatTo = null;//跟谁对话
var chatToBussId = null;
var imgNext = ui("imgNext");
page.on({name:"transport"}, function(data, e) {
	var chat2User = data;//这里可能是用户或群组(因为单聊和群聊共用这个top)
	chatType = data.type;
	chatTo = chat2User.imId;
	ui("labelTitle").text = chat2User.name;
	if(data.type=="Chat"){
		chatToBussId = chat2User.userId;
		ui("headerCircle").hide();
		ui("headerRight").visible = false;
		/*
		imgNext.source="source://image/im/single.png";
		ui("headerRight").on("touch", function() {
			open.openPersonal(chat2User.userId);//到他的主页
		});
		*/
	}else if(data.type=="GroupChat"){
		chatToBussId = chat2User.groupId;
		imgNext.source="source://image/im/group.png";
		ui("headerRight").visible = true;
		ui("headerRight").on("touch", function() {
			if(chat2User.groupId){
				imHelper.toGroupMember(chat2User.groupId);//去圈子成员列表 或 群聊成员列表
			}
		});
		
		httpSilence.post(circleUrl.url.base.isGroupChat, {id:chat2User.groupId}, function(data) {
			var isGroupChat = data.isGroupChat;
			if (isGroupChat) {
				ui("headerCircle").hide();//如果单纯是群聊，不显是圈子链拉
			}else{
				//如果是圈子的群聊，显示【圈子】链接
				ui("headerCircle").show();
				ui("headerCircle").on("touch", function() {
					if(chat2User.groupId){
						var circleId = chat2User.groupId;
						var circleName = chat2User.name;
						circleHelper.toCircleDetail(circleId,circleName);
					}
				});
			}
		});
	}
})

//更改群聊名称
app.on("chat_name_update",function(data, e) {
	//deviceone.print("chat_name_update")
	if(data.chatId && data.chatId == chatToBussId){
		if(data.chatName!=null){
			ui("labelTitle").text = data.chatName;
		}
	}
})